package com.ionafan2.iaccepteuromaidan;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class LoginActivity extends Activity {

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private RequestPostTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    private String deviseId;

    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);

        setContentView(R.layout.activity_login);

        deviseId = Utils.getDeviceId(this);
        preferences = getSharedPreferences("auth", MODE_APPEND);

        // for developing
        preferences.edit().clear().commit();

        if (!TextUtils.isEmpty(preferences.getString(Const.AUTH_TOKEN, ""))) {
            Intent intent = new Intent(this, VotingActivity.class);
            startActivity(intent);
        }

        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mEmailView.setAdapter(getEmailAddressAdapter(this));

        mPasswordView = (EditText) findViewById(R.id.password);

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(preferences.getString(Const.AUTH_TOKEN, ""))) {
                    Intent intent = new Intent(LoginActivity.this, VotingActivity.class);
                    startActivity(intent);
                }

                attemptLogin();
            }
        });
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (!checkPasswordRequired()) {
            focusView = mPasswordView;
            cancel = true;
        }

        if (!checkEmail()) {
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);

            ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

            nameValuePair.add(new BasicNameValuePair("email", mEmail));
            nameValuePair.add(new BasicNameValuePair("password", mPassword));
            nameValuePair.add(new BasicNameValuePair("device_id", deviseId));

            mAuthTask = new RequestPostTask(nameValuePair).setOnRequestTaskListener(new PostTaskListener());
            mAuthTask.execute(Settings.SIGNUP_SIGNING_URL);
        }
    }

    private boolean checkEmail() {
        if (TextUtils.isEmpty(mEmailView.getText())) {
            mEmailView.setError(this.getString(R.string.error_field_required));
            return false;
        }
        if (!Settings.EMAIL_ADDRESS_PATTERN.matcher(mEmailView.getText()).matches()) {
            mEmailView.setError(this.getString(R.string.error_invalid_email));
            return false;
        }
        return true;
    }

    private boolean checkPasswordRequired() {
        if (TextUtils.isEmpty(mPasswordView.getText())) {
            mPasswordView.setError(this.getString(R.string.error_field_required));
            return false;
        }
        return true;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {

        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);

        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    public class PostTaskListener implements RequestPostTaskListener {
        @Override
        public void onDataLoaded(String responseJsonString) {

            if (responseJsonString != null && responseJsonString.length() != 0) {

                try {
                    JSONObject responseObject = new JSONObject(responseJsonString);
                    JSend jSend = new JSend();

                    if (jSend.isValid(responseObject)) {
                        if (responseObject.get(JSend.STATUS).equals(JSend.SUCCESS)) {

                            JSONObject responseJsonData = new JSONObject(responseObject.get(JSend.DATA).toString());

                            preferences.edit()
                                       .putString(Const.AUTH_TOKEN, responseJsonData.get("token").toString())
                                       .commit();
                            mAuthTask = null;
                            showProgress(false);
                            Intent intent = new Intent(LoginActivity.this, VotingActivity.class);
                            startActivity(intent);
                        } else if (responseObject.get(JSend.STATUS).equals(JSend.FAIL)) {
                            mAuthTask = null;
                            showProgress(false);
                            Toast.makeText(LoginActivity.this, responseObject.optString(JSend.DATA), Toast.LENGTH_LONG).show();
                        } else if (responseObject.get(JSend.STATUS).equals(JSend.ERROR)) {
                            mAuthTask = null;
                            showProgress(false);
                            Toast.makeText(LoginActivity.this, responseObject.optString(JSend.MESSAGE), Toast.LENGTH_LONG).show();
                        }
                    } else {
                        mAuthTask = null;
                        showProgress(false);
                        Toast.makeText(LoginActivity.this, "JSend is invalid!", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                mAuthTask = null;
                showProgress(false);
                Toast.makeText(LoginActivity.this, "Empty response.", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    private ArrayAdapter<String> getEmailAddressAdapter(Context context) {
        Account[] accounts = AccountManager.get(context).getAccountsByType("com.google");
        String[] addresses = new String[accounts.length];
        for (int i = 0; i < accounts.length; i++) {
            addresses[i] = accounts[i].name;
        }
        return new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, addresses);
    }
}
